package com.wisewin.circle.util.payUtil;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.wisewin.circle.util.aliPay.AlipayConfig;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class AliPayUtil {

    //实例化客户端
    static AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APP_ID,
            AlipayConfig.APP_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET,
            AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGN_TYPE);

    //获取支付支付参数
    public static String getAliPayParam(String attach, BigDecimal money, String orderNumber, String notifyUrl) {

        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody("alipay");
        model.setSubject("appraisal");
        //生成订单号
        model.setOutTradeNo(orderNumber);
        //model.setTimeoutExpress("30m"); 订单最晚支付时间，若为空，则默认为15d
        model.setTotalAmount(money + ""); //订单金额
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl(AlipayConfig.NOTIFY_URL + notifyUrl);//回调地址

        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            if (response.isSuccess()) {
                System.err.println(response.getBody());
                return response.getBody();
            }
            System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }


    // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，
    // 调用RSA签名方式
    static AlipayTradeAppPayRequest ali_request = new AlipayTradeAppPayRequest();
    // 封装请求支付信息
    static AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();

    public static String getAliPayParam2(String attach, BigDecimal money, String orderNumber, String notifyUrl) throws AlipayApiException {
        model.setSubject("currency");
        model.setOutTradeNo(orderNumber);
        model.setTotalAmount(money.toString());
        model.setProductCode("QUICK_MSECURITY_PAY");
        ali_request.setBizModel(model);
        ali_request.setNotifyUrl(AlipayConfig.NOTIFY_URL + notifyUrl);
        // 调用SDK生成表单
        AlipayTradeAppPayResponse ali_response = alipayClient.sdkExecute(ali_request);
        if (ali_response.isSuccess()) {
            System.out.println("获取参数成功====");
            return ali_response.getBody();

        } else {
            System.out.println("获取参数失败====");
            throw new AlipayApiException("调用SDK生成表单失败");
        }

    }

    /**
     * 验证是否支付成功
     */
    public static boolean isPaySuccessful(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {

        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        //log.info("支付宝验签:{}", jsonString4JavaPOJO);

        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        String out_trade_no = request.getParameter("out_trade_no");            // 商户订单号
        String trade_no = request.getParameter("trade_no");            // 流水号
        String tradeStatus = request.getParameter("trade_status");
        String total_amount = request.getParameter("total_amount");  //订单金额

        //签名验证(对支付宝返回的数据验证，确定是支付宝返回的)
        boolean signVerified = false;
        try {
            //3.1调用SDK验证签名
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGN_TYPE);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //4.对验签进行处理
        if (signVerified) {    //验签通过
            if (tradeStatus.equals("TRADE_SUCCESS")) {    //只处理支付成功的订单: 修改交易表状态,支付成功
                return true;
            }
        }
        return false;
    }
}